// pages/dcDetails/dcDetails.js
const app = getApp()
//const user = JSON.parse(wx.getStorageSync("user"));
const base_url = app.globalData.base_url;
const util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:false,
    userid:'',
    isConfirm:false,//提交表白
    isdialog:false,//打开对话框
    total:'',//打赏总值
    yb_num:'',//元宝个数
    other:'',//两数
    dog_list:'',//列表
    dog_name:[],//狗名列表
    selDog:false,
    index:0,//选中狗的下标
    dog_id:'',
    barWidth:'0%',//宽度
    userInfo:{},
    page:{
      p:0,
      psize:3
    },
    showPic:[],
    photo_num:'',//写真总数
    formlove:{},//表白数据
    reward:{
      my:{},
      first:{},
      second:{},
      third:{},
      other:[]
    },//打赏榜
    is_close:0,//下拉收起
    show:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      dog_id:options.id,
      userid:options.userid,
      shars: options.shars
    })
    this.init()
    // wx.getSystemInfo({
    //   success: res => {
    //     let windowHeight = (res.windowHeight * (750 / res.windowWidth));
    //     this.setData({
    //       hei: windowHeight - 650 - 32
    //     })
    //   }
    // })
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.init(true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (ops) {
    let _this=this;
    if (ops.from === 'button') {
      let id = this.data.id;
      // 来自页面内转发按钮
      return {
        title: '大家一起来看看哈，我家的老狗',
        path: '/pages/dcDetails/dcDetails?id=' + this.data.dog_id + "&userid=" + this.data.user_id+"&shars=1",
        success: function (res) {
         _this.setData({
           show:false
         })
          // 转发成功
          // var shareTickets = res.shareTickets;
          // if (shareTickets.length == 0) {
          //   return false;
          // }
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function (res) {
              var encryptedData = res.encryptedData;
              var iv = res.iv;
            }
          })
        },
        fail: function (res) {
          // 转发失败
          wx.showToast({
            icon: 'none',
            title: '转发失败',
          })
        }

      }
    }
  },
  myCatchTouch(){
    return false;
  },
  move: function () {},
  getUser(id){//狗主人信息
    wx.request({
      url: base_url + '/Public/getUserInfoById',
      data: {
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: res => {
        if(res.data.success == 1){
          this.getList();
          this.setData({
            userInfo:res.data.data
          })
        }
      }
    })
  },
  init(refresh = false){
    wx.showLoading({
      title: '加载中',
      mask:true,
      success:()=>{
        wx.request({
          url: base_url + '/Dog/detail',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'dog_id':this.data.dog_id,
            'p': this.data.page.p,
            'psize': this.data.page.psize
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: res => {
            if (res.data.success == '1') {
              this.setData({
                dcArr: res.data.data
              })
              this.getUser(this.data.dcArr.user_id)
              wx.setNavigationBarTitle({
                title: res.data.data.dog_name
              })
              let yb = parseInt(res.data.data.yuanbao_sum),All;
              if (yb >= 10000) {
                All = (yb / 10000).toFixed(1)
              } else {
                All = yb
              }
              this.setData({
                total:Number(yb),
                yb_num: Math.floor(parseInt(yb) / 100),
                other:parseInt(yb%100),
                barWidth: parseInt(yb)/100 +'%',
                All:All
              });
              // 更新表白列表
              if(this.data.dcArr.is_edit == 0){//他人的狗牌页面
                wx.request({
                  url: base_url + '/Dog/getMyDog',
                  data: {
                    'user_token': JSON.parse(wx.getStorageSync("user")).user_token
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  success: res => {
                      if(res.data.success == 1){
                        let dog_name = res.data.data.map(v=>{
                          return v.dog_name
                        })
                        this.setData({
                          dog_name:dog_name,
                          dog_list: res.data.data
                        })
                      }
                  }
                })
              }
              refresh == true && wx.stopPullDownRefresh();
            } else {
              wx.showToast({
                title: '加载失败',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },
  dels(e) {
    wx.showLoading({
      success: () => {
        wx.request({
          url: base_url + '/Dog/del',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'dog_id': this.data.dog_id,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: res => {
            if (res.data.success == '1') {
              wx.showToast({
                title: '移除成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(e=>{
                wx.navigateTo({
                  url: '/pages/dogCard/dogCard'
                })
              },1000)
            } else {
              wx.showToast({
                title: '移除失败',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },
  confirm:function(e){
    if (this.data.formlove.identity == ''){
      wx.showToast({
        title: '请输入表白身份',
        icon:'none',
        duration:2000
      })
      return 
    }
    wx.showModal({
      title: '提示',
      content: '确认向对方表白？',
      success: (res) => {
        if (res.confirm) {//表白请求
          // console.log('用户点击确定')
          let formlove = this.data.formlove;
          formlove.user_token = JSON.parse(wx.getStorageSync("user")).user_token;
          formlove.pro_dog_id = this.data.dog_list[this.data.index].dog_id;
          formlove.dog_id = this.data.dog_id;
          formlove.form_id = e.detail.formId;
          wx.showLoading({
            title: '正在发送',
            mask:true,
            success:()=>{
              wx.request({
                url: base_url + '/Profess/add',
                data: formlove,
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                success: res => {
                  if (res.data.success ==1) {
                    this.setData({//表白成功提示
                      isConfirm: true,
                      isdialog:false,
                      'formlove.content':""
                    })
                    wx.navigateBack({
                      delta: 1
                    })
                  }else{
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                  wx.hideLoading();
                }
              })
            }
          })
         
        } else if (res.cancel) {
          wx.showToast({
            title: '取消表白',
            icon:'none',
            duration:2000
          })
        }
      }
    })

  },
  forlove:function(){
    this.setData({
      isdialog: true,
      isConfirm: false
    })
  },
  confirmout(){
    this.setData({
      isdialog: false,
      isConfirm: false
    })
  },
  imgYu(){
    this.init();
    let _this=this;
    setTimeout(e=>{
      // let list = [this.data.dcArr.share_img],
      //   img = this.data.dcArr.share_img;
      // wx.previewImage({
      //   current: img,
      //   urls: list
      // })
      wx.downloadFile({
        url: this.data.dcArr.share_img, //仅为示例，并非真实的资源
        success: function (res) {
          console.log(res)
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            wx.playVoice({
              filePath: res.tempFilePath
            })
          }
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.showModal({
                title: '保存成功',
                content: '保存成功',
              })
              _this.setData({
                show: false
              })
            },
          })
        }
      })
    },500)
    
  },
  qx(){
    this.setData({
      show:false
    })
  },
  want() {
    wx.navigateTo({
      url: '../dogCard/dogCard?id=' + this.data.userInfo.user_id
    })
  },
  toindex(){
     wx.navigateTo({
      url: '../index/index'
    })
  },
  reward(){
    // let reward = Math.random() * 9 + 1;
        wx.showLoading({
          success: () => {
            wx.request({
              url: base_url + '/Dog/reward',
              data: {
                'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
                'dog_id': this.data.dog_id,
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              method: 'POST',
              success: res => {
                wx.hideLoading();
                if(res.data.success == '1'){
                  let number = Number(res.data.data.number);//本次打赏数量
                  let total = number + Number(this.data.total);//计算打赏总值
                    wx.showToast({
                      title: "打赏成功!",
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(e=>{
                      this.init();
                    },1000)
                     
                    // this.setData({
                    //   yb_num: parseInt(total / 100),
                    //   other: total % 100,
                    //   barWidth: total % 100 + '%',
                    //   total: total
                    // })
                    // this.getList()
                }else{
                  wx.showToast({
                    title: res.data.msg,
                    icon:'none',
                    duration:2000
                  })
                }

              }
            })
        }
      })
  },
  code(){
    this.setData({
      show:true
    })
    // wx.navigateTo({
    //   url: '/pages/code/code?id=' +  this.data.dog_id,
    // })
    // wx.showActionSheet({
    //   itemList: ['发给微信好友', '保存狗卡二维码'],
    //   success: res => {
    //     if (res.tapIndex == 0) {

    //     } else {

    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res.errMsg)
    //   }
    // }) 
  },
  edit(){
    wx.navigateTo({
      url: '/pages/addDogCard/addDogCard?id=' + this.data.dog_id,
    })
  },
  getList(){
    wx.showLoading({
      title: '加载中',
      mask:true,
      success:()=>{
        wx.request({
          url: base_url + '/Dog/getRewardList',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'dog_id': this.data.dog_id,
            'p':0,
            'psize':3
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: res => {
            this.getPhoto();
            if (res.data.success == '1') {
              let reward = this.data.reward;
              let data = res.data.data;
              reward.my = data.filter(v=>{
                return v.is_my_rank == 1 ? v : ''
              })[0]
              reward.first = data.filter(v => {
                return v.rank == 1 && v.is_my_rank != 1 ? v : ''
              })[0]
              reward.second = data.filter(v => {
                return v.rank == 2 && v.is_my_rank != 1 ? v : ''
              })[0]
              reward.third = data.filter(v => {
                return v.rank == 3 && v.is_my_rank != 1 ? v : ''
              })[0]
              reward.other = data.filter(v => {
                return v.rank != 1 && v.rank != 2 && v.rank != 3 
              })
              this.setData({
                reward:reward
              })
            }

          }
        })
      }
    })
  },
  close: function (e) {
    this.setData({
      isdialog: false,
      is_close:e.currentTarget.dataset.type
    })
  },
  picDetail:function(){
    wx.navigateTo({
      url: '../picDetails/picDetails?id='+this.data.dog_id
    })
  },
  getPhoto:function(){
    wx.showLoading({
      title: '加载中',
      success:()=>{
        wx.request({
          url: base_url + '/Photo/getList',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'dog_id': this.data.dog_id,
            'p': this.data.page.p,
            'psize': this.data.page.psize
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success:(res)=>{
            if(res.data.success == 1){
              wx.hideLoading();
              this.setData({
                showPic:res.data.data.photo_list,
                photo_num: res.data.data.photo_num
              })
            }
          }
        })
      }
    })
  },
  bindPickerChange(e){
    this.setData({
      index: e.detail.value,
      selDog: true,
    })
    
  },
  setlove(e){
    let type = e.currentTarget.dataset.type;
    let label = 'formlove.'+type;
    this.setData({
      [label]: e.detail.value
    })
  },
  // 收入家庭
  addFamily(){
    let http = () => {
      wx.showLoading({
        success:()=>{
          wx.request({
            url: base_url + '/Dog/collectOrCancel',
            data: {
              'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
              'dog_id': this.data.dog_id,
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            success: (res) => {
              if (res.data.success == 1) {
                this.setData({
                  'dcArr.is_collect': this.data.dcArr.is_collect == 0 ? 1 : 0
                })
                wx.showToast({
                  title: '操作成功',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
              wx.hideLoading();
            }
          })
        }
      })
      
    };
    if(this.data.dcArr.is_collect == 1){
      wx.showModal({
        title: '提示',
        content: '是否移除' + this.data.dcArr.dog_name,
        success: res => {
          if (res.confirm) {
            http();
          } else if (res.cancel) {
            wx.showToast({
              title: '已取消移除',
              icon:'none',
              duration:2000
            })
          }
        }
      })
    }else{
      http()
    }
   
  }
})